package com.nut.course.service.impl;

import com.nut.course.common.Result;
import com.nut.course.entity.OssFile;
import com.nut.course.mapper.SysOssFileMapper;
import com.nut.course.service.SystemService;
import com.nut.course.util.OssUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class SystemServiceImpl implements SystemService {

    @Autowired
    private SysOssFileMapper sysOssFileMapper;

    @Override
    public Result uploadFile(MultipartFile multipartFile) {


        return null;
    }

    @Override
    public Result<OssFile> uploadImg(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();

        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        String contentType = null;
        if (ext.equals("jpg")) {
            contentType = OssUtils.CONTENT_TYPE_JPG;
        } else if (ext.equals("png")) {
            contentType = OssUtils.CONTENT_TYPE_PNG;
        }

        String fileName = OssUtils.generateFileName(ext);
        try {
            String fileUrl = OssUtils.uploadFile(fileName, multipartFile.getInputStream(), contentType);

            OssFile ossFile = new OssFile();
            ossFile.setName(fileName);
            ossFile.setUrl(fileUrl);
            ossFile.setSize(multipartFile.getSize());
            ossFile.setExt(ext);
            sysOssFileMapper.insert(ossFile);

            return Result.ok(ossFile);
        } catch (Exception e) {
            log.error("uploadImg_error", e);
            return Result.fail(e.getMessage());
        }

    }


}
